package com.pie4cloud.pie.job.executor.utils.ftp;

import com.pie4cloud.pie.job.api.entity.ConfigFtp;
import com.pie4cloud.pie.job.executor.utils.FtpClient;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class FtpUtil {

	private  ConcurrentHashMap<Long, FtpProcessor> ftps=new ConcurrentHashMap<>();

	public FtpProcessor getFtpProcessor(ConfigFtp configFtp){
		if(null!=ftps.get(configFtp.getFtpId())){
			return ftps.get(configFtp.getFtpId());
		}else {
			synchronized (this){
				if(null!=ftps.get(configFtp.getFtpId())){
					return ftps.get(configFtp.getFtpId());
				}else {
					GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
					poolConfig.setTestOnBorrow(true);
					poolConfig.setTestOnReturn(true);
					poolConfig.setTestWhileIdle(true);
					poolConfig.setMinEvictableIdleTimeMillis(6000);
					poolConfig.setSoftMinEvictableIdleTimeMillis(50000);
					poolConfig.setTimeBetweenEvictionRunsMillis(30000);
					FtpProperties ftpProperties=new FtpProperties();
					ftpProperties.setIp(configFtp.getFtpAddress());
					ftpProperties.setPort(String.valueOf(configFtp.getFtpPort()));
					ftpProperties.setUsername(configFtp.getFtpUserName());
					ftpProperties.setPassword(configFtp.getFtpPwd());
					ObjectPool<FTPClient> pool = new GenericObjectPool<>(new FtpClientPooledObjectFactory(ftpProperties), poolConfig);
					FtpProcessor processor = new FtpProcessor(ftpProperties);
					processor.setFtpClientPool(pool);
					processor.setHasInit(true);
					ftps.put(configFtp.getFtpId(),processor);
					return processor;
				}
			}
		}

	}


}
